import fs from 'fs';
import path from 'path';
import Koa from 'koa';
import favicon from 'koa-favicon';
import serve from 'koa-static';
import compress from 'koa-compress';
import logger from 'koa-morgan';
import bodyParser from 'koa-body';
import ejs from 'koa-ejs';
import jwt from 'koa-jwt';
import Component from './ZES';
import Index from './routes/index';
import {
    JWT_SECRET
} from './routes/user';
import Model from './model';
import db from './db';

const PROJECT_BASE = path.join(__dirname, '..');
console.log('BASEDIR:', PROJECT_BASE);

const app = new Koa();
Component.init(app);
app.context.model = Model;
app.context.db = db;

ejs(app, {
    root: path.join(PROJECT_BASE, 'view'),
    layout: false,
    viewExt: 'ejs',
    cache: false,
    debug: false
});


// uncomment after placing your favicon in /public

app.use(favicon(path.join(PROJECT_BASE, 'view', 'favicon.png')));
app.use(serve(path.join(PROJECT_BASE), {
    extensions: false,
    hidden: true
}));
app.use(serve(path.join(PROJECT_BASE, 'view'), {
    extensions: false,
    hidden: true
}));
app.use(compress());
app.use(logger('combined', fs.createWriteStream(PROJECT_BASE + '/logs/access.log', {
    flags: 'a'
})));
app.use(bodyParser());


app.use(jwt({
    secret: JWT_SECRET,
    passthrough: true,
    cookie: 'rc-auth'
}));



let index = new Index();
app.use(index.routes());

app.on('error', err => {
    console.error(err);
});



// eslint-disable-next-line no-magic-numbers
app.listen(3001);
module.exports = app;
console.log('started');

//RequestContext.printAll();
